<?php
/**
 * 用户
 * 
 * Created	: 2010-12-22
 * Modified : 2010-12-22
 * @author  : 陈立强
 */
class Skill {
	public static $tbl = 'user_skill';
	
	/**
	 * 技能学习
	 * @param int $uid
	 * @param int $skill_id
	 */
	public static function study($uid, $skillId)
	{
		global $DB, $L;
		$sql = 'SELECT us_id, skill_lvl FROM user_skill WHERE uid='.$uid.' and skill_id='.$skillId;
		$skill = $DB->getValue($sql);
		if ($skill) {
			return array(
				'val' => false,
				'msg' => $L['skill_had_studied'],
			);
		}
		$skillList = C('skill/skill');
		if (!isset($skillList[$skillId])) {
			return array(
				'val' => false,
				'msg' => $L['skill_not_exists'],
			);
		}
		$data = array(
			'uid'      => $uid,
			'skill_id' => $skillId,
			'skill_lvl' => 1,
			'skill_exp' => 0,
			'skill_type' => $skillList[$skillId]['type'],
		);
		$ret = $DB->insert('user_skill', $data);
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$result['data'] = $data;
		} else {
			$result['msg'] = $L['Failure'];
			// 记录错误日志
			Log::save('user_add_exp', $data);
		}
		
		return $result;
	}
	
	/**
	 * 是否已学习技能
	 * @param int $uid
	 * @param int $skillId
	 */
	public static function isStudied($uid, $skillId) 
	{
		global $DB, $L;
		$sql = 'SELECT us_id FROM user_skill WHERE uid='.$uid.' and skill_id='.$skillId;
		$exists = $DB->getValue($sql);
		return (bool)$exists;
	}

	/**
	 * 添加技能熟练度
	 * @param int $uid 玩家ID
	 * @param int $skillId 技能ID
	 * @param int $exp 增加的经验值
	 */
	public static function addExp($uid, $skillId, $exp)
	{
		global $DB, $L;

		$uid     = (int)$uid;
		$skillId = (int)$skillId;
		$exp     = (int)$exp;

		$skillList = C('skill');
		$skillInfo = $skillList[$skillId];

		$sql  = 'SELECT * FROM '.self::$tbl.' WHERE uid='.$uid.' and skill_id='.$skillId;
		$info = $DB->getValue($sql);

		$skillExpCfg = C('skill_exp');
		$maxExp = $skillExpCfg[$info['skill_lvl']];
		$maxLvl = $skillExpCfg[$info['skill_max_lvl']];

		$skillLvl = $info['skill_lvl'];
		$skillExp = $info['skill_exp'] + $exp;

		// 满经验了
		if ($skillLvl == $maxLvl && $skillExp > $maxExp) {
			$newExp = $maxExp;
		} elseif ($skillExp > $maxExp) {
			$skillExp -= $maxExp;
			$skillLvl++;
			for ($i=$skillLvl; $i<=$skillInfo['max_lvl']; $i++) {
				if ($skillExp < $skillExpCfg[$i]) {
					break;
				} else {
					$skillExp -= $skillExpCfg[$i];
					$skillLvl++;
				}
			}
		}
		
		$data = array(
			'skill_lvl' => $skillLvl,
			'skill_exp' => $skillExp
		);
		$where = 'us_id='.$info['us_id'];
		$ret = $DB->update(self::$tbl, $data, $where);
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$result['data'] = $data;
		} else {
			$result['msg'] = $L['Failure'];
			// 记录错误日志
			Log::save('user_add_exp', $data);
		}
		return $result;
	}
}